from threading import RLock
from Code.XmlData import XmlData
from Code.XmlDataOperationCSV import XmlDataOperationCSV
from Code.XmlDataOperationMDB import XmlDataOperationMDB
from Code.XmlDataOperationXLSX import XmlDataOperationXLSX


class XmlDataManager:
    single_lock = RLock()

    def __init__(self):
            self.xmlDataList = []

    def push_data(self, path, type):
        xmlData = XmlData(path, type)
        self.xmlDataList.append(xmlData)

    def __new__(cls, *args, **kwargs):
        with XmlDataManager.single_lock:
            if not hasattr(XmlDataManager, "_instance"):
                XmlDataManager._instance = object.__new__(cls)

        return XmlDataManager._instance

    def handle_all_data(self):
        result = {}
        for i in range(0, len(self.xmlDataList)):
            xmlData = self.xmlDataList[i]
            if xmlData.type == "CSV":
                xmlDataOperation = XmlDataOperationCSV()

            elif xmlData.type == "XLSX":
               xmlDataOperation = XmlDataOperationXLSX()

            elif xmlData.type == "MDB":
               xmlDataOperation = XmlDataOperationMDB()

            dataDic =  xmlDataOperation.handle_file(xmlData.path)

            for key, value in dataDic.items():
                if key in result:
                    result[key] += value
                else:
                    result[key] = value

        return result